package bblnamed

import (
	"encoding/json"
	"io/ioutil"
	"os"
	"path/filepath"
)

var server_conf ServerConfig

//var gateway_conf []GatewayConfig

type ServerConfig struct {
	UUID       string   `json:"cluster.uuid"`
	Name       string   `json:"cluster.name"`
	Listen     string   `json:"cluster.listen"`
	Slaves     []string `json:"cluster.slaves"`
	Master     string   `json:"cluster.master"`
	Workdir    string   `json:"cluster.workdir"`
	Replicas   int      `json:"cluster.replicas"`
	Passphrase string   `json:"cluster.passphrase"`
	LogLevel   string   `json:"log.level"`
	LogFile    string   `json:"log.file"`
	_file      string
}

// type GatewayConfig struct {
// 	Address string
// 	Perm    string
// }

func init_config(config string) error {
	filePath, err := filepath.Abs(config)
	if err != nil {
		return err
	}
	conf, err := read_config(filePath)
	if err != nil {
		return err
	}
	conf._file = filePath
	server_conf = conf
	// gconf, err := load_gateway(filepath.Dir(filePath) + "/bblcluster_gateway.conf")
	// if err != nil {
	// 	return err
	// }
	// gateway_conf = gconf
	return nil
}

// func load_gateway(file string) (gws []GatewayConfig, e error) {
// 	b, e := ioutil.ReadFile(file)
// 	if e != nil {
// 		return config, e
// 	}
// 	e = json.Unmarshal(b, &gws)
// 	return
// }

func read_config(file string) (config ServerConfig, e error) {
	b, e := ioutil.ReadFile(file)
	if e != nil {
		return config, e
	}
	e = json.Unmarshal(b, &config)
	return
}

func write_config(config ServerConfig) error {
	b, e := json.Marshal(config)
	if e != nil {
		return e
	}
	e = ioutil.WriteFile(config._file, b, os.ModePerm)
	if e != nil {
		return e
	}
	server_conf = config
	return nil
}
